﻿using EyFramework.Common;
using EyFramework.Sys.Core;
using Ncov2019.Core.Dao;
using Ncov2019.Entity;
using System;
using System.Collections.Generic;
using System.Threading;
using Newtonsoft.Json;
using RestSharp;
using Ncov2019.Entity.Dto;

namespace Ncov2019.Core.Service
{
    /// <summary>
    ///  NCOV_ORDER_RECORD表的服务实现类
    /// </summary>
    public class NcovOrderRecordService : BaseHisService, INcovOrderRecordService
    {
        protected readonly INcovOrderRecordDao _NcovOrderRecordDao;

        private INcovUsersService ncovUsersService;

        private INcovOrderRecordService ncovOrderRecordService;

        public NcovOrderRecordService(INcovOrderRecordDao ncovOrderRecordDao)
        {
            _NcovOrderRecordDao = ncovOrderRecordDao;
            ncovUsersService = Globals.GetService<INcovUsersService>();
        }

        public bool AddNcovUsers(long record_seq, List<NcovUsersDto> ncovUsers)
        {
            _NcovOrderRecordDao.BeginTrans();
            try
            {
                ncovUsers.ForEach(p =>
                {
                    NcovOrderRecord ncovOrderRecord = new NcovOrderRecord();
                    ncovOrderRecord.ORDER_SEQ = GetHisMaxId("NCOV_ORDER_RECORD", "ORDER_SEQ");
                    ncovOrderRecord.PAT_SEQ = p.PAT_SEQ;
                    ncovOrderRecord.CHT_ID = p.CHT_ID;
                    ncovOrderRecord.RECORD_SEQ = record_seq;
                    ncovOrderRecord.PAT_NM = p.PAT_NM;
                    ncovOrderRecord.DEPARTMENT = p.DEPARTMENT;
                    ncovOrderRecord.SEX = p.SEX;
                    ncovOrderRecord.BIRTHDAY = p.BIRTHDAY;
                    ncovOrderRecord.ID_NO = p.ID_NO;
                    ncovOrderRecord.TELPHONE = p.TELPHONE;
                    ncovOrderRecord.PAT_TAGS = p.PAT_TAGS;
                    _NcovOrderRecordDao.Insert(ncovOrderRecord);
                });
                _NcovOrderRecordDao.CommitTrans();
                return true;
            }
            catch (Exception ex)
            {
                _NcovOrderRecordDao.RollBackTrans();
                throw new BizException("添加核酸检查对象失败!" + ex.ToString());
            }
        }

        public bool ClearOrders(long record_seq)
        {
            return _NcovOrderRecordDao.ClearOrders(record_seq);
        }

        public bool DeleteOrders(List<NcovOrderRecordDto> orders)
        {
            return _NcovOrderRecordDao.DeleteOrders(orders);
        }

        public bool LisOrder(NcovOrderRecordDto order)
        {
            try
            {
                _NcovOrderRecordDao.BeginTrans();
                //1、调用检验开单,调用Lis的存储过程
                LisOrderProParam orderParam = new LisOrderProParam();
                orderParam.PRM_JIUZHENHAO = order.CHT_ID;
                orderParam.PRM_SHENFENZH = order.ID_NO;
                orderParam.PRM_JIUZHENLX = "3";
                orderParam.PRM_XINGMING = order.PAT_NM;
                orderParam.PRM_XINGBIE = order.SEX;
                orderParam.PRM_CHUSHENGRQ = Convert.ToDateTime(order.BIRTHDAY);
                orderParam.PRM_DIANHUAHM = order.TELPHONE;
                orderParam.PRM_ZHENDUANMC = "实验室检查";
                orderParam.PRM_KAIDANKSID = "110105";
                orderParam.PRM_KAIDANKSMC = "呼吸内科";
                orderParam.PRM_KAIDANYSID = "800148";
                orderParam.PRM_KAIDANYSXM = "杨月汉";
                orderParam.PRM_KAIDANSJ = DateTime.Now;
                orderParam.PRM_JIANYANXMDM = "429";
                orderParam.PRM_JIANYANXMMC = "COVID-19检测(免费)";
                orderParam.PRM_DAYINRID = "800132";
                orderParam.PRM_DAYINRXM = "张伟东";
                orderParam.PRM_DAYINSJ = DateTime.Now;

                //调用存储过程实现开单
                bool result = _NcovOrderRecordDao.LisOrder(orderParam);
                if (result)
                {
                    order.BAR_NO = orderParam.PRM_TIAOMAHAO;
                    order.ORD_DT = orderParam.PRM_DAYINSJ;
                    order.ORD_USR_ID = Globals.CurrentUser.UserId;
                    update(order);
                }
                _NcovOrderRecordDao.CommitTrans();
                return true;
            }
            catch (Exception ex)
            {
                _NcovOrderRecordDao.RollBackTrans();
                throw new BizException("生成检验条码失败", ex);
            }
        }

        public List<NcovOrderRecordDto> QueryDataByRecSeq(long detailDataSeq)
        {
            return _NcovOrderRecordDao.QueryDataByRecSeq(detailDataSeq);
        }

        public List<long> QueryHasImport(long record_seq)
        {
            return _NcovOrderRecordDao.QueryHasImport(record_seq);
        }

        public void update(NcovOrderRecordDto ncovOrder)
        {
            _NcovOrderRecordDao.Update(ncovOrder);
        }

        /// <summary>
        /// 免费核酸开单
        /// </summary>
        /// <returns></returns>
        public bool NcovFreeOrder(NcovFreeOrderParam orderParam)
        {
            string currentDateStr = GetCurrentDate("yyyy-MM-dd HH:mm:ss");
            DateTime currentDateTime = Convert.ToDateTime(currentDateStr);
            //调用核酸开单
            NcovFreeOrder order = new NcovFreeOrder()
            {
                hos_code = "0001",
                name = orderParam.PatName,
                idcard_type = "01",
                idcard_value = orderParam.IdNo,
                age = Globals.GetAge(Convert.ToDateTime(orderParam.Birthday), currentDateTime)
                    .ToString(),
                gender = orderParam.Sex,
                birthday = orderParam.Birthday,
                phone = orderParam.Telphone,
                address = orderParam.Address,
                out_city_travel = "0",
                out_country_travel = "0",
                access_dangerous_areas = "0",
                access_dangerous_people = "0",
                fever_symptom = "0",
                access_npc_people = "0",
                access_fever_people = "0",
                vehicle = "0",
                temperature = "36.5",
                fever_status = "0",
                tosse = "0",
                shortness_breath = "0",
                take_drug = "0",
                take_fever_drug = "0",
                disease = "",
                examine_purpose = "5",
                health_code = orderParam.Healthcode,
                residence_address = orderParam.Address,
                prov = "浙江省",
                city = "杭州市",
                county = "萧山区",
                district = "瓜沥镇",
                other_address = "",
                project_no_lists = "429"
            };
            var orderReturn = NcovOrder(order);
            //开单成功，判断是否已经传递到检验系统
            if (!LisHasReady(orderReturn.reservation_no, orderReturn.record_no))
            {
                throw new BizException("开单成功,Lis消息获取超时,请重新开单");
            }
            //调用支付
            string tradeno = "Free" + GetCurrentDate("yyyyMMddHHmmss");
            PayNcovOrder payNcovOrder = new PayNcovOrder()
            {
                order_no = orderReturn.order_no,
                hos_code = "0001",
                trade_no = tradeno,
                pay_channel_trade_no = tradeno,
                pay_channel = "1",
                pay_time = currentDateStr,
                pay_amount = "0",
                record_no = orderReturn.record_no
            };
            //调用付费
            PayNocvOrderReturn payNocvOrderReturn = PayNcovFreeeOrder(payNcovOrder);
            orderParam.Bingrenid = orderReturn.record_no;
            //支付成功以后，保存开单记录
            NcovOrderRecord ncovRecord = new NcovOrderRecord()
            {
                ORDER_SEQ = GetHisMaxId("NCOV_ORDER_RECORD", "ORDER_SEQ"),
                PAT_SEQ = orderParam.Patseq,
                CHT_ID = orderReturn.record_no,
                ORD_DT = currentDateTime,
                ORD_USR_ID = Globals.CurrentUser.UserId,
                PAT_NM = orderParam.PatName,
                DEPARTMENT = "老派出所采样点",
                DATESEQ = orderReturn.order_no,
                SEX = orderParam.Sex,
                BIRTHDAY = orderParam.Birthday,
                ID_NO = orderParam.IdNo,
                TELPHONE = orderParam.Telphone,
                BAR_NO = orderReturn.reservation_no,
                PAT_TYPE = "10"
            };
            this._NcovOrderRecordDao.Insert(ncovRecord);
            return true;
        }

        /// <summary>
        /// 判断是否LIS是否已经收到消息
        /// </summary>
        /// <param name="jiuzhenid"></param>
        /// <param name="bingrenid"></param>
        /// <returns></returns>
        private bool LisHasReady(string jiuzhenid, string bingrenid)
        {
            int waitSecond = 0;
            bool hasReady = false;
            while (waitSecond < 30 && !hasReady)
            {
                Thread.Sleep(2000);
                hasReady = _NcovOrderRecordDao.LisHasReady(jiuzhenid, bingrenid);
                waitSecond++;
            }
            return hasReady;
        }

        /// <summary>
        /// 核酸开单
        /// </summary>
        /// <param name="ncovFreeOrder"></param>
        /// <returns></returns>
        private NcovFreeOrderReturn NcovOrder(NcovFreeOrder ncovFreeOrder)
        {
            var client = new RestClient("http://192.168.0.125:9004/");
            var request = new RestRequest("Api/HeSuanKD", Method.POST);
            request.AddParameter("application/json", JsonConvert.SerializeObject(ncovFreeOrder), ParameterType.RequestBody);
            var retObj = client.Post(request);
            NcovFreeOrderReturn ncovFreeOrderReturn =
                JsonConvert.DeserializeObject<NcovFreeOrderReturn>(retObj.Content);
            if (ncovFreeOrderReturn.response_code != "1")
            {
                if (ncovFreeOrderReturn.response_msg == "没有找到病人信息")
                {
                    ncovFreeOrderReturn = NcovOrder(ncovFreeOrder);
                    if (ncovFreeOrderReturn.response_code != "1")
                    {
                        throw new Exception("核酸开单失败!" + ncovFreeOrderReturn.response_msg);
                    }
                }
                else
                {
                    throw new Exception("核酸开单失败!" + ncovFreeOrderReturn.response_msg);
                }
            }
            return ncovFreeOrderReturn;
        }

        /// <summary>
        /// 核酸开单支付
        /// </summary>
        /// <param name="payNcovOrder"></param>
        /// <returns></returns>
        public PayNocvOrderReturn PayNcovFreeeOrder(PayNcovOrder payNcovOrder)
        {
            var client = new RestClient("http://192.168.0.125:9004/");
            var request = new RestRequest("Api/HeSuanJS", Method.POST);
            request.AddParameter("application/json", JsonConvert.SerializeObject(payNcovOrder), ParameterType.RequestBody);
            var retObj = client.Post(request);
            PayNocvOrderReturn ncovPayNocvOrderReturn =
                JsonConvert.DeserializeObject<PayNocvOrderReturn>(retObj.Content);
            if (ncovPayNocvOrderReturn.response_code != "1")
            {
                throw new Exception("付费支付失败!" + ncovPayNocvOrderReturn.response_msg);
            }
            return ncovPayNocvOrderReturn;
        }

        public bool CancelNcovFreeOrder(NcovOrderCacnel ncovOrderCacnel)
        {
            var client = new RestClient("http://192.168.0.125:9008/");
            var request = new RestRequest("Api/HeSuanQXKD", Method.POST);
            request.AddParameter("application/json", JsonConvert.SerializeObject(ncovOrderCacnel), ParameterType.RequestBody);
            var retObj = client.Post(request);
            return true;
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public List<NcovOrderRecord> QueryData(NcovRecordParam param)
        {
            return _NcovOrderRecordDao.QueryDataBy(param);
        }

        public List<GyBingrenxxDto> SearchBrxx(string sInput)
        {
            return _NcovOrderRecordDao.SearchBrxx(sInput);
        }

        /// <summary>
        /// 根据身份证号获取最后一次未打印的条码
        /// </summary>
        /// <param name="shenFenZh"></param>
        /// <returns></returns>
        public NcovOrderRecord QueryLastByIdNo(string shenFenZh)
        {
            return _NcovOrderRecordDao.QueryLastByIdNo(shenFenZh);
        }

        public bool NcovOrder(NcovOrderRecordDto ncovOrder)
        {
            //1、获取档案信息
            if (string.IsNullOrEmpty(ncovOrder.CHT_ID))
            {
                ncovOrder.CHT_ID = GetChtId();
                var ncovUser = ncovUsersService.SelectByPatseq(ncovOrder.PAT_SEQ);
                if (ncovUser == null)
                {
                    throw new BizException(string.Format("没有找到档案流水号为{0}的档案信息", ncovOrder.PAT_SEQ));
                }
                ncovUser.CHT_ID = ncovOrder.CHT_ID;
                ncovUsersService.UpdateNcovUser(ncovUser);
            }
            LisOrder(ncovOrder);
            if (string.IsNullOrEmpty(ncovOrder.BAR_NO))
            {
                throw new BizException(string.Format("生成条码号失败，用户{0}", ncovOrder.PAT_NM));
            }

            //记录开单记录
            //更新档案信息
            return true;
        }

        /**
         * 判断当前条码的状态是否有效
         */

        public bool IsValid(NcovOrderRecordDto order)
        {
            return true;
        }

        /// <summary>
        /// 获取档案号
        /// </summary>
        /// <returns></returns>
        public string GetChtId()
        {
            long Seq = GetHisMaxId("Reg_Cht_Pat", "Cht_Id");
            return "8" + Seq.ToString().PadLeft(7, '0');
        }
    }
}